<template>
  <div class="user-manage">
    <div class="header">
      <h2>用户管理</h2>
      <el-button type="primary" @click="addUser">新增用户</el-button>
    </div>

    <!-- 搜索区域 -->
    <div class="search-container">
      <el-input
        v-model="searchQuery"
        placeholder="请输入姓名、手机号、业主姓名或楼栋房间号"
        clearable
        :prefix-icon="Search"
        @keyup.enter="handleSearch"
      >
        <template #append>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
        </template>
      </el-input>
    </div>

    <div class="table-wrapper">
      <el-table class="user-table" :data="showPage.records" border stripe>
        <el-table-column
          prop="realname"
          label="姓名"
          fixed="left"
          min-width="80"
          show-overflow-tooltip
        />
        <el-table-column prop="phone" label="手机号" min-width="130" show-overflow-tooltip />
        <el-table-column prop="building" label="楼栋号" />
        <el-table-column prop="room" label="房间号" />
        <el-table-column prop="residentNature" label="业主关系" />
        <el-table-column label="状态" min-width="80">
          <template #default="{ row }">
            <el-tag :type="getTagColor(row.status)">
              {{ getStateTxt(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" min-width="180">
          <template #default="{ row }">
            <el-button size="small" @click="editUser(row)">编辑</el-button>
            <el-popconfirm title="确定删除?" @confirm="delUser(row.uid)">
              <template #reference>
                <el-button size="small" type="danger">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        size="small"
        layout="prev, pager, next"
        :page-size="pageController.size"
        :total="showPage.total"
        @change="handlePageChange"
      />
    </div>

    <!-- 编辑抽屉 -->
    <el-drawer
      class="right-drawer"
      v-model="showDrawer"
      :title="isAdd ? '新增用户' : '编辑用户'"
      @closed="onDrawerClose"
      size="400"
    >
      <el-form :model="form" label-width="90">
        <el-row class="building-room-row">
          <el-form-item class="building-room-item" label="楼栋号">
            <el-input
              v-model="form.building"
              placeholder="楼栋号"
              @blur="handleBuildingRoomChange"
              :disabled="!isAdd"
            >
              <template #append>栋</template>
            </el-input>
          </el-form-item>
          <el-form-item label="房间号">
            <el-input
              v-model="form.room"
              placeholder="房间号"
              @blur="handleBuildingRoomChange"
              :disabled="!isAdd"
            />
          </el-form-item>
        </el-row>
        <el-form-item label="房屋业主">
          <el-input v-model="form.ownerName" placeholder="房屋业主的姓名" disabled />
        </el-form-item>
        <el-form-item label="姓名">
          <el-input v-model="form.realname" />
        </el-form-item>
        <el-form-item label="性别">
          <el-select v-model="form.gender" placeholder="请选择" :options="genderOptions" />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="form.phone" maxlength="11" />
        </el-form-item>
        <el-form-item label="业主关系">
          <el-select v-model="form.residentNature" placeholder="请选择">
            <el-option
              v-for="(item, index) in residentNatureList"
              :key="index"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="form.status" :options="userStatusOptions" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="handleDrawoerCancel">取消</el-button>
        <el-button type="primary" @click="saveUser">保存</el-button>
      </template>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import { Search } from '@element-plus/icons-vue'
import { apiRegister, apiMUserList, apiOwnerFromRoom, apiMUserUpdate } from '@/api/manager'
import { userStatusOptions, type MUser } from '@/model/manager'
import type { ReqPage, ResPage } from '@/model/request'
import { genderOptions, residentNatureList } from '@/model/user'
import { ref, type Ref, onMounted } from 'vue'
import { apiUserDelete } from '@/api/user'

// 初始化数据
const showPage: Ref<ResPage<MUser>> = ref({
  current: 1,
  pages: 0,
  records: [],
  size: 5,
  total: 0,
})

const pageController: Ref<ReqPage> = ref({
  current: 1, // 实际由分页组件控制
  size: 5,
  search: new Map(),
})

const reflushPage = () => {
  apiMUserList(pageController.value).then((result) => {
    showPage.value = result
  })
}

const handlePageChange = (value: number) => {
  console.log('page change', value, pageController.value.size)

  pageController.value.current = value

  const page: ReqPage = {
    ...pageController.value,
  }

  console.log(page)

  reflushPage()
}

const getTagColor = (status: number) => {
  switch (status) {
    case 1:
      return 'success'
    case 0:
      return 'info'
    case 2:
      return 'warning'
    default:
      return 'info'
  }
}

const getStateTxt = (status: number) => {
  switch (status) {
    case 1:
      return '启用'
    case 0:
      return '禁用'
    case 2:
      return '待审核'
    default:
      return 'unknown'
  }
}

// 搜索相关
const searchQuery = ref('')

const handleSearch = () => {
  // TODO: 搜索逻辑通过computed自动处理，这里可以添加额外逻辑如防抖等

  const search = searchQuery.value.trim()

  if (search === undefined || search === '') return

  console.log('search', search)

  pageController.value.likeAll = search

  console.log(JSON.stringify(pageController.value))

  reflushPage()
}

const showDrawer = ref(false)
const isAdd = ref(true)

// 表单默认值
const defaultForm: MUser = {
  uid: 0,
  realname: '',
  phone: '',
  gender: 1,
  building: '',
  room: '',
  residentNature: '业主',
  ownerName: '',
  role: 1,
  status: 1,
  create_time: 0,
}

const form = ref<MUser>({ ...defaultForm })

const addUser = () => {
  isAdd.value = true
  showDrawer.value = true
}

const editUser = async (row: MUser) => {
  isAdd.value = false
  form.value = { ...row }
  form.value.building = row.building.split('栋')[0]
  if (row.ownerName == undefined || row.ownerName === '') {
    const ownerName = await apiOwnerFromRoom(row.building, row.room)
    form.value.ownerName = ownerName.ownerName
  }
  showDrawer.value = true
}

const handleBuildingRoomChange = () => {
  if (form.value.building === defaultForm.building || form.value.room === defaultForm.room) {
    return
  }
  // 触发自动搜索房屋的业主
  apiOwnerFromRoom(form.value.building, form.value.room)
    .then((user) => {
      form.value.ownerName = user.ownerName
    })
    .catch((error: Error) => {
      form.value.ownerName = error.message
    })
}

const onDrawerClose = () => {
  if (!isAdd.value) {
    form.value = defaultForm
  }
}

const handleDrawoerCancel = () => {
  showDrawer.value = false
  form.value = { ...defaultForm }
}

const saveUser = async () => {
  const newUser: MUser = {
    ...form.value,
  }
  newUser.building = `${newUser.building}栋`

  if (isAdd.value) {
    await apiRegister(newUser)
  } else {
    await apiMUserUpdate(newUser)
  }
  // 刷新表格
  reflushPage()

  showDrawer.value = false
}

const delUser = async (uid: number) => {
  await apiUserDelete(uid)
  reflushPage()
}

onMounted(() => {
  form.value = { ...defaultForm }
  reflushPage()
})
</script>

<style scoped lang="scss">
.user-manage {
  width: 100%;
  padding: 24px;
  background: #fafafa;
  display: flex;
  flex-direction: column;
  gap: 16px;

  > * {
    width: 100%;
  }
}
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-container {
  :deep(.el-input) {
    width: 600px;
  }
}

.table-wrapper {
  width: 100%;
  overflow: auto;
}

.user-table {
  :deep(.cell) {
    text-align: center;
  }
}

.building-room-row {
  > * {
    width: 50%;
  }
}

.right-drawer {
  :deep(.el-select) {
    width: 100%;
  }

  .building-room-item {
    :deep(.el-input-group__append) {
      padding: 0 8px;
    }
  }
}
</style>
